<template>
  <div class="dicom-dynamic-page">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2 class="page-title">动态DICOM加载</h2>
      </div>
      <div class="toolbar-right">
        <div class="connection-status">
          <span class="status-indicator" :class="{ 'connected': orthancConnected, 'disconnected': !orthancConnected }">
            {{ orthancConnected ? '🟢' : '🔴' }}
          </span>
          <span class="status-text">
            {{ orthancConnected ? 'Orthanc已连接' : 'Orthanc未连接' }}
          </span>
        </div>
        
        <button 
          class="refresh-btn" 
          @click="refreshStudyList" 
          :disabled="loading"
        >
          刷新列表
        </button>
        
        <button 
          class="explore-btn" 
          @click="exploreOrthanc" 
          :disabled="!orthancConnected || loading"
        >
          探索数据
        </button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧研究列表 -->
      <div class="study-list-panel">
        <div class="panel-header">
          <h3>研究列表</h3>
          <span class="study-count">{{ studies.length }} 个研究</span>
        </div>
        
        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <div class="loading-text">正在加载研究列表...</div>
        </div>
        
        <div v-else-if="studies.length === 0" class="empty-state">
          <div class="empty-icon">📁</div>
          <div class="empty-title">没有找到研究</div>
          <div class="empty-subtitle">请确保Orthanc中有DICOM数据</div>
          <button class="empty-btn" @click="refreshStudyList">
            重新加载
          </button>
        </div>
        
        <div v-else class="study-list">
          <div 
            v-for="study in studies" 
            :key="study.id"
            class="study-item"
            :class="{ 'selected': selectedStudy?.id === study.id }"
            @click="selectStudy(study)"
          >
            <div class="study-info">
              <div class="study-title">
                {{ study.PatientMainDicomTags?.PatientName || 'Unknown Patient' }}
              </div>
              <div class="study-subtitle">
                {{ study.MainDicomTags?.StudyDescription || 'No Description' }}
              </div>
              <div class="study-meta">
                <span class="study-date">{{ formatDate(study.MainDicomTags?.StudyDate) }}</span>
                <span class="series-count">{{ study.Series?.length || 0 }} 个系列</span>
              </div>
            </div>
            <div class="study-actions">
              <button class="action-btn" @click.stop="loadStudyPreview(study)">
                预览
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧查看器区域 -->
      <div class="viewer-panel">
        <div v-if="!selectedStudy" class="empty-viewer">
          <div class="empty-content">
            <div class="empty-icon">🖼️</div>
            <div class="empty-title">请选择一个研究</div>
            <div class="empty-subtitle">从左侧列表中选择要查看的研究</div>
          </div>
        </div>
        
        <div v-else class="study-viewer">
          <!-- 研究信息 -->
          <div class="study-header">
            <h3>{{ selectedStudy.PatientMainDicomTags?.PatientName || 'Unknown Patient' }}</h3>
            <p>{{ selectedStudy.MainDicomTags?.StudyDescription || 'No Description' }}</p>
          </div>
          
          <!-- 系列网格 -->
          <div class="series-grid">
            <div 
              v-for="series in selectedStudySeries" 
              :key="series.id"
              class="series-card"
              @click="loadSeriesImages(series)"
            >
              <div class="series-thumbnail">
                <img 
                  v-if="series.thumbnailUrl" 
                  :src="series.thumbnailUrl" 
                  alt="Series Thumbnail"
                  @error="handleImageError"
                />
                <div v-else class="thumbnail-placeholder">
                  <i class="material-icons">image</i>
                </div>
              </div>
              
              <div class="series-info">
                <div class="series-title">
                  {{ series.MainDicomTags?.SeriesDescription || 'No Description' }}
                </div>
                <div class="series-meta">
                  <span class="modality">{{ series.MainDicomTags?.Modality || 'Unknown' }}</span>
                  <span class="instance-count">{{ series.Instances?.length || 0 }} 张图像</span>
                </div>
              </div>
              
              <div class="series-actions">
                <button class="load-btn" @click.stop="loadSeriesImages(series)">
                  加载
                </button>
              </div>
            </div>
          </div>
          
          <!-- 图像查看器 -->
          <div v-if="currentImages.length > 0" class="image-viewer">
            <div class="viewer-header">
              <h4>图像查看器</h4>
              <div class="viewer-controls">
                <button @click="previousImage" :disabled="currentImageIndex <= 0">
                  上一张
                </button>
                <span class="image-counter">
                  {{ currentImageIndex + 1 }} / {{ currentImages.length }}
                </span>
                <button @click="nextImage" :disabled="currentImageIndex >= currentImages.length - 1">
                  下一张
                </button>
              </div>
            </div>
            
            <div class="image-display">
              <img 
                v-if="currentImages[currentImageIndex]" 
                :src="currentImages[currentImageIndex].url" 
                alt="DICOM Image"
                class="dicom-image"
                @load="handleImageLoad"
                @error="handleImageError"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { orthancService } from '@/services/orthanc.service'
import { fullOrthancExploration } from '@/utils/orthanc-api-explorer'

// 响应式数据
const orthancConnected = ref(false)
const loading = ref(false)
const studies = ref<any[]>([])
const selectedStudy = ref<any>(null)
const selectedStudySeries = ref<any[]>([])
const currentImages = ref<any[]>([])
const currentImageIndex = ref(0)

// 计算属性
const hasData = computed(() => studies.value.length > 0)

// 测试Orthanc连接
const testConnection = async () => {
  try {
    orthancConnected.value = await orthancService.testConnection()
  } catch (error) {
    console.error('连接测试失败:', error)
    orthancConnected.value = false
  }
}

// 刷新研究列表
const refreshStudyList = async () => {
  loading.value = true
  try {
    console.log('🔄 刷新研究列表...')
    const studyList = await orthancService.getStudies()
    studies.value = studyList
    console.log(`✅ 加载了 ${studyList.length} 个研究`)
  } catch (error) {
    console.error('获取研究列表失败:', error)
    studies.value = []
  } finally {
    loading.value = false
  }
}

// 探索Orthanc数据
const exploreOrthanc = async () => {
  loading.value = true
  try {
    console.log('🔍 开始探索Orthanc数据...')
    await fullOrthancExploration()
    // 探索完成后刷新列表
    await refreshStudyList()
  } catch (error) {
    console.error('探索Orthanc失败:', error)
  } finally {
    loading.value = false
  }
}

// 选择研究
const selectStudy = async (study: any) => {
  selectedStudy.value = study
  currentImages.value = []
  currentImageIndex.value = 0
  
  try {
    console.log(`📖 选择研究: ${study.id}`)
    
    // 获取研究的系列信息
    const seriesPromises = study.Series.map(async (seriesId: string) => {
      try {
        const response = await fetch(`/api/orthanc/series/${seriesId}`)
        const seriesData = await response.json()
        
        // 尝试获取缩略图
        try {
          const thumbnailResponse = await fetch(`/api/orthanc/series/${seriesId}/instances`)
          const instances = await thumbnailResponse.json()
          if (instances.length > 0) {
            const firstInstanceResponse = await fetch(`/api/orthanc/instances/${instances[0]}`)
            const instanceData = await firstInstanceResponse.json()
            seriesData.thumbnailUrl = `/api/orthanc/instances/${instances[0]}/preview`
          }
        } catch (error) {
          console.warn('获取缩略图失败:', error)
        }
        
        return {
          id: seriesId,
          ...seriesData
        }
      } catch (error) {
        console.error(`获取系列失败 ${seriesId}:`, error)
        return null
      }
    })
    
    const seriesResults = await Promise.all(seriesPromises)
    selectedStudySeries.value = seriesResults.filter(s => s !== null)
    
    console.log(`✅ 加载了 ${selectedStudySeries.value.length} 个系列`)
  } catch (error) {
    console.error('选择研究失败:', error)
    selectedStudySeries.value = []
  }
}

// 加载研究预览
const loadStudyPreview = async (study: any) => {
  console.log(`👁️ 预览研究: ${study.id}`)
  await selectStudy(study)
}

// 加载系列图像
const loadSeriesImages = async (series: any) => {
  try {
    console.log(`🖼️ 加载系列图像: ${series.id}`)
    
    const instances = series.Instances || []
    const imagePromises = instances.map(async (instanceId: string) => {
      try {
        return {
          id: instanceId,
          url: `/api/orthanc/instances/${instanceId}/preview`
        }
      } catch (error) {
        console.error(`加载实例失败 ${instanceId}:`, error)
        return null
      }
    })
    
    const imageResults = await Promise.all(imagePromises)
    currentImages.value = imageResults.filter(img => img !== null)
    currentImageIndex.value = 0
    
    console.log(`✅ 加载了 ${currentImages.value.length} 张图像`)
  } catch (error) {
    console.error('加载系列图像失败:', error)
    currentImages.value = []
  }
}

// 图像导航
const previousImage = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--
  }
}

const nextImage = () => {
  if (currentImageIndex.value < currentImages.value.length - 1) {
    currentImageIndex.value++
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return 'Unknown Date'
  
  // DICOM日期格式: YYYYMMDD
  if (dateStr.length === 8) {
    const year = dateStr.substring(0, 4)
    const month = dateStr.substring(4, 6)
    const day = dateStr.substring(6, 8)
    return `${year}-${month}-${day}`
  }
  
  return dateStr
}

// 图像加载处理
const handleImageLoad = () => {
  console.log('图像加载成功')
}

const handleImageError = (event: Event) => {
  console.error('图像加载失败:', event)
}

// 生命周期
onMounted(async () => {
  console.log('🚀 初始化动态DICOM加载器')
  
  await testConnection()
  
  if (orthancConnected.value) {
    await refreshStudyList()
  }
})
</script>

<style scoped>
.dicom-dynamic-page {
  height: 100%;
  width: 100%;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
}

/* 工具栏 */
.toolbar {
  height: 60px;
  background: white;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.status-indicator {
  font-size: 12px;
}

.status-text {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.refresh-btn, .explore-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.refresh-btn:hover, .explore-btn:hover {
  background: #0056b3;
}

.refresh-btn:disabled, .explore-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

/* 主内容区 */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 研究列表面板 */
.study-list-panel {
  width: 350px;
  background: white;
  border-right: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.study-count {
  font-size: 12px;
  color: #666;
  background: #f8f9fa;
  padding: 4px 8px;
  border-radius: 12px;
}

.study-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.study-item {
  padding: 12px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.study-item:hover {
  background: #f8f9fa;
  border-color: #007bff;
}

.study-item.selected {
  background: #e3f2fd;
  border-color: #007bff;
}

.study-info {
  flex: 1;
}

.study-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.study-subtitle {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.study-meta {
  display: flex;
  gap: 12px;
  font-size: 11px;
  color: #999;
}

.study-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  background: #28a745;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 11px;
  cursor: pointer;
}

.action-btn:hover {
  background: #218838;
}

/* 查看器面板 */
.viewer-panel {
  flex: 1;
  background: white;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.empty-viewer {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-content {
  text-align: center;
  padding: 40px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.empty-subtitle {
  font-size: 14px;
  color: #666;
}

.study-viewer {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow: hidden;
}

.study-header {
  margin-bottom: 20px;
}

.study-header h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.study-header p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

/* 系列网格 */
.series-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.series-card {
  border: 1px solid #e9ecef;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s;
}

.series-card:hover {
  border-color: #007bff;
  box-shadow: 0 2px 8px rgba(0,123,255,0.1);
}

.series-thumbnail {
  height: 120px;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.series-thumbnail img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.thumbnail-placeholder {
  color: #ccc;
  font-size: 48px;
}

.series-info {
  padding: 12px;
}

.series-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.series-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.series-actions {
  padding: 0 12px 12px;
}

.load-btn {
  width: 100%;
  background: #007bff;
  color: white;
  border: none;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.load-btn:hover {
  background: #0056b3;
}

/* 图像查看器 */
.image-viewer {
  flex: 1;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.viewer-header {
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.viewer-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.viewer-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.viewer-controls button {
  background: #007bff;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.viewer-controls button:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.image-counter {
  font-size: 12px;
  color: #666;
  min-width: 80px;
  text-align: center;
}

.image-display {
  flex: 1;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.dicom-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

/* 加载和空状态 */
.loading-state, .empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 14px;
  color: #666;
}

.empty-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  margin-top: 16px;
}

.empty-btn:hover {
  background: #0056b3;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .study-list-panel {
    width: 100%;
    height: 300px;
  }
  
  .series-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style>


